#install.packages("microsynth")
#install.packages("readstata13")
library(microsynth)
library(readstata13)
library("dplyr")
library(Hmisc)
require(foreign)
#vignete
#https://cran.r-project.org/web/packages/microsynth/microsynth.pdf
wd = getwd()
my_data <- read.dta13(paste(wd ,"/data/data_for_weighting.dta", sep = ""))
ipv_data <- read.dta13(paste(wd ,"/data/ipv_data_for_weighting.dta", sep = ""))

mycov.var <- c('age', 'age_partner', 'hh_members' , 'sec_complete', 'children_lockdown','income_hh2019')
my1 <- microsynth(my_data,
                   idvar='merge_id_num', timevar='year', intvar='not_nber',
                   end.pre=2019, 
                   match.covar=mycov.var,
                   result.var=FALSE, 
                   test='lower',
                   )


#normalize to match means in other group
my_data$unnormalized_weights = my1$w$Weights


subset = my_data[c('merge_id', 'unnormalized_weights')]
write.dta(subset, paste(wd ,"/data/synth_weights.dta", sep = ""))



myipv <- microsynth(ipv_data,
                  idvar='merge_id_num', timevar='year', intvar='not_nber',
                  end.pre=2019, 
                  match.covar=c('dPhy', 'dPsy','dAll'),
                  result.var=FALSE, 
                  test='lower',
)


#normalize to match means in other group
ipv_data$unnormalized_weights_ipv = myipv$w$Weights

subset_ipv = ipv_data[c('merge_id', 'unnormalized_weights_ipv')]
write.dta(ipv_data, paste(wd ,"/data/synth_weights_ipv.dta", sep = ""))




